package com.lagou.util;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoding extends MessageToByteEncoder {
    private Class<?> clazz;

    private Serializer serializer;

    public RpcEncoding(Class<?> clazz, Serializer serializer){
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
            if (clazz != null && clazz.isInstance(o)){
                byte[] bytes = serializer.serialize(o);
                //buf前四个字节存放的是数据长度
                byteBuf.writeInt(bytes.length);
                //再将数据写入到buf中
                byteBuf.writeBytes(bytes);
            }
    }
}
